package com.ruoyi.web.controller.topic;



import com.ruoyi.system.domain.Tag;
import com.ruoyi.system.domain.vo.Result;
import com.ruoyi.system.service.TagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;


@Api(tags = "标签模块")
@RequestMapping("/api")
@RestController
public class TagController extends BaseController{

    @Autowired
    private TagService tagService;

    @GetMapping("/tags/id/{id}")
    @ApiOperation("根据ID查询标签")
    public Result<Tag> getTagById(@PathVariable("id") Long id){
        return Result.success(tagService.getTagById(id));
    }

        @GetMapping("/tags/name/{name}")
    @ApiOperation("根据NAME查询标签")
    public Result<Tag> getTagById(@PathVariable("name") String name){
        return Result.success(tagService.getTagByName(name));
    }

    @ApiOperation("获得所有标签")
    @GetMapping("/tags")
    public Result<List<Tag>> getAllTag(){
        return Result.success(tagService.getAllTag());
    }

    @ApiOperation("添加标签")
    @PostMapping("/tags/input")
    public Result<?> addTag(Tag tag, RedirectAttributes attributes){
        Tag tagByName = tagService.getTagByName(tag.getNames());
        if(tagByName!=null){
            attributes.addFlashAttribute("message","不能添加重复标签");
            Result.fail("添加失败！");
        }
        int t = tagService.saveTag(tag);
        if(t==0){
            attributes.addFlashAttribute("message","新增失败");
        }
        else {
            attributes.addFlashAttribute("message","新增成功");
        }
        return Result.success();
    }

    @ApiOperation("修改标签")
    @PostMapping("/tags/{id}")
    public Result<?> updateTag(Tag tag,@PathVariable("id") Long id,RedirectAttributes attributes){
        Tag tagByName = tagService.getTagByName(tag.getNames());
        if(tagByName!=null){
            attributes.addFlashAttribute("message","不能添加重复标签");
            Result.fail("修改失败！");
        }
        int t = tagService.updateTag(tag);
        if(t==0){
            attributes.addFlashAttribute("message","修改失败");
        }
        else {
            attributes.addFlashAttribute("message","修改成功");
        }
        return Result.success();
    }

    @ApiOperation("删除标签")
    @PostMapping("/tags/{id}/delete")
    public Result<?> deleteTag(@PathVariable("id") Long id){
        tagService.deleteTag(id);
        return Result.success();
    }

}
